from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey, Enum
from sqlalchemy.sql import func
from sqlalchemy.orm import relationship
import enum
from app.database.base import Base

class MessageRole(str, enum.Enum):
    """消息角色枚举"""
    USER = "user"       # 用户
    AI = "ai"           # AI
    SYSTEM = "system"   # 系统

class ChatSession(Base):
    """聊天会话模型"""
    __tablename__ = "chat_sessions"
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    # 关联用户ID，外键
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    # 会话名称
    name = Column(String(100), nullable=False)
    # 会话描述
    description = Column(String(500), nullable=True)
    # 创建时间
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    # 更新时间
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    # 关联消息记录（一对多）
    messages = relationship("ChatMessage", back_populates="session", cascade="all, delete-orphan")
    # 关联用户
    user = relationship("User", backref="chat_sessions")

class ChatMessage(Base):
    """聊天消息模型"""
    __tablename__ = "chat_messages"
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    # 关联会话ID，外键
    session_id = Column(Integer, ForeignKey("chat_sessions.id"), nullable=False)
    # 消息角色（用户/AI/系统）
    role = Column(Enum(MessageRole), nullable=False)
    # 消息内容
    content = Column(Text, nullable=False)
    # 消息ID（用于追踪）
    message_id = Column(String(100), index=True, nullable=True)
    # 创建时间
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    
    # 关联会话
    session = relationship("ChatSession", back_populates="messages")
